package com.moment.util;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.xml.sax.SAXException;

public class Geocoding
{
	public String GetLatlong(String addr)throws IOException, XPathExpressionException, ParserConfigurationException, SAXException 
	{
	// URL prefix to the geocoder
	final String GEOCODER_REQUEST_PREFIX_FOR_XML = "http://maps.google.com/maps/api/geocode/xml";
	String ss = null;
	
		
	{
		//	query address
		//String origAddress = "C/13/97, MIG COLONY, BANDRA (EAST), MUMBAI 400051, India";
		// String origAddress = "Kituluni, Machakos, Kenya";
		// String origAddress = "Naivasha, Kenya";

		System.out.println("Original address : " + addr);
		
		//	prepare a URL to the geocoder
		URL url = new URL(GEOCODER_REQUEST_PREFIX_FOR_XML + "?address=" + 
				URLEncoder.encode(addr, "UTF-8") + "&sensor=false");

		//	prepare an HTTP connection to the geocoder
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//Document geocoderResultDocument = null;
		Document docOrigAddress = null;

		try
		{
			// open the connection and get results as InputSource.
			conn.connect();
			InputSource geocoderResultInputSource = new InputSource(conn.getInputStream());
			// read result and parse into XML Document
			docOrigAddress = 
				DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(geocoderResultInputSource);
		}
		finally 
		{
			conn.disconnect();
		}

		// prepare XPath
		XPath xpath = XPathFactory.newInstance().newXPath();

		// extract the result
		NodeList addressList = null;

		// a) obtain the formatted_address field for every result
		addressList = (NodeList) xpath.evaluate(
				"/GeocodeResponse/result/formatted_address", 
				docOrigAddress, XPathConstants.NODESET);

		int addresses = addressList.getLength();
		System.out.println("Formatted addresses : " + addresses);

		for(int address = 0; address < addresses; address++) 
		{
			Document docAddress = docOrigAddress;
		
			System.out.println("\nFormatted address " + address + " : " 
					+ addressList.item(address).getTextContent());
			// b) extract the locality for the first result
			NodeList localityList = null;
			localityList = (NodeList) xpath.evaluate(
					"/GeocodeResponse/result[" + (address + 1) + 
					"]/address_component[type/text()='locality']/long_name", 
					docAddress, XPathConstants.NODESET);

			int localities = localityList.getLength();
			for(int locality = 0; locality  < localities; locality++) 
			{
				Document docLocality = docAddress;
				System.out.println("Locality : " 
						+ localityList.item(locality).getTextContent());
				// c) extract the coordinates of the first result
				NodeList locationList = null;
				locationList = (NodeList) xpath.evaluate(
						"/GeocodeResponse/result[" + (address + 1) + 
						"]/geometry/location/*", 
						docLocality,
						XPathConstants.NODESET);

				int locations = locationList.getLength();
				float lat = Float.NaN;
				float lng = Float.NaN;
		
				for(int location = 0; location < locations; location++) 
				{
					Node node = locationList.item(location);
					if("lat".equals(node.getNodeName()))
						lat = Float.parseFloat(node.getTextContent());
					if("lng".equals(node.getNodeName()))
						lng = Float.parseFloat(node.getTextContent());
				}
				 ss=String.valueOf(lat)+ ","+ String.valueOf(lng);
				System.out.printf("latitude = %.15f, longitude = %.15f\n", lat, lng);
			}
		}
	}
	return ss;
	
}
}